<?php

namespace common\modules\user\models\frontend;

use common\modules\user\Module;
use common\modules\user\helpers\Security;
use common\modules\user\models\User;
use yii\db\ActiveRecord;
use Yii;

/**
 * Class Email
 *
 * @property integer $user_id User ID
 * @property string  $email   E-mail
 * @property string  $token   Confirmation token
 */
class Email extends ActiveRecord
{

    /**
     * @var string Current e-mail address
     */
    private $_oldemail;

    /**
     * @var static Email model instance
     */
    private $_model;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%user_email}}';
    }

    /**
     * @return string Current e-mail address
     */
    public function getOldemail()
    {
        if ($this->_oldemail === null)
        {
            $this->_oldemail = Yii::$app->user->identity->email;
        }
        return $this->_oldemail;
    }

    /**
     * Generates secure key.
     */
    public function generateToken()
    {
        $this->token = Security::generateExpiringRandomString();
    }

    /**
     * Check if token is valid.
     *
     * @return boolean true if token is valid
     */
    public function isValidToken()
    {
        if (Security::isValidToken($this->token, Module::current()->emailWithin) === true)
        {
            return ($this->_model = static::findOne(['token' => $this->token])) !== null;
        }
        return false;
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            // E-mail
            ['email', 'required'],
            ['email', 'trim'],
            ['email', 'email'],
            ['email', 'string', 'max' => 100],
            ['email', 'compare', 'compareAttribute' => 'oldemail', 'operator' => '!=='],
            ['email', 'unique', 'targetClass' => User::className()],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'email'    => Module::t('user', 'ATTR_NEW_EMAIL'),
            'oldemail' => Module::t('user', 'ATTR_OLDEMAIL'),
        ];
    }

    /**
     * @return \common\modules\user\models\frontend\User|null 关联用户
     */
    public function getUser()
    {
        return $this->hasOne(User::className(), ['id' => 'user_id']);
    }

    /**
     * @inheritdoc
     */
    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert))
        {
            static::deleteAll(['user_id' => Yii::$app->user->identity->getId()]);
            $this->user_id = Yii::$app->user->identity->getId();
            $this->generateToken();
            $this->send();

            return true;
        }
        return false;
    }

    /**
     * Confirm email change.
     *
     * @return boolean true if email was successfully confirmed.
     */
    public function confirm()
    {
        $model = $this->_model;
        $user = $model->user;
        $user->email = $model->email;
        return $user->save(false) && $model->delete();
    }

    /**
     * Send an email confirmation token.
     *
     * @return boolean true if email confirmation token was successfully sent
     */
    public function send()
    {
        return $this->module->mail
            ->compose('email', ['model' => $this])
            ->setTo($this->email)
            ->setSubject(Module::t('user', 'EMAIL_SUBJECT_CHANGE') . ' ' . Yii::$app->name)
            ->send();
    }
}
